<!--
 * @Author: toString muzi_li0323@163.com
 * @Date: 2024-05-22 20:22:04
 * @LastEditors: toString muzi_li0323@163.com
 * @LastEditTime: 2024-05-23 19:58:24
 * @FilePath: /chain-link-api-front/src/views/reg/index.vue
 * @Description: Reg
-->
<template>
  <div class="container block login">
    <!--    左侧表单 start -->
    <div class="box left-box reg-form">

      <!-- Logo -->
      <TopLogo></TopLogo>
      <div class="main">
        <div class="login-title">
          {{ t('global.UserSignUp') }}
        </div>

        <el-form :model="forms" ref="ruleRef" label-width="auto" :rules="rules" label-position="top">
          <el-form-item :label="t('global.UserName')" prop="username" style="width: 100%">
            <el-input v-model.trim="forms.username" :placeholder="t('global.PleaseInputUserName')"/>
          </el-form-item>
          <el-form-item :label="t('global.Email')" prop="email" style="width: 100%">
            <el-input v-model.trim="forms.email" type="text" :placeholder="t('message.PleaseInputEmail')"/>
          </el-form-item>
          <el-form-item :label="t('global.Code')" prop="emailCode" style="width: 100%">
            <el-input v-model.trim="forms.emailCode" type="text" :placeholder="t('message.PleaseInputCode')">
              <template #suffix>
                <el-button type="primary" link @click="getCode" :disabled="countdown.value">{{countdownText }}</el-button>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label="t('global.PassWord')" prop="password1" style="width:100%">
            <el-input v-model.trim="forms.password1" type="password" show-password :placeholder="t('message.PleaseInputPWD')"/>
          </el-form-item>
          <el-form-item :label="t('global.ConfirmPassWord')" prop="password2" style="width:100%;">
            <el-input v-model.trim="forms.password2" type="password" show-password :placeholder="t('message.ConfirmPWD')"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" class="submit_btn" @click="submit">{{ t('home.Register') }}</el-button>
          </el-form-item>
        </el-form>
      </div>

      <login-footer :footerType="'reg'"></login-footer>
    </div>

    <RightImg></RightImg>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useUserStore } from "@/stores";
import { ElMessage } from "element-plus";
import TopLogo from '@/components/LoginCom/TopLogo.vue';
import LoginFooter from "@/components/LoginCom/loginFooter.vue";
import RightImg from '@/components/LoginCom/RightImg.vue';
import { useRouter } from "vue-router";
import { register, getEmailCode } from "@/require/api.js";

import { useI18n } from "vue-i18n";

const { t } = useI18n();

const userStore = useUserStore();
const router = useRouter();
const countdownText = ref(t('global.GetCode'))
const countdown = ref(0);
const ruleRef = ref(null);
const footerType = ref('reg')

// 获取验证码
async function getCode() {
  // 验证邮箱格式是否正确
  ruleRef.value.validateField('email', async ( valid ) => {
    if (!valid) {
      ElMessage.error(t("message.CheckEmail"));
      return false;
    }
    countdown.value = 60;
    countdownText.value = t('global.ReSend') + countdown.value + 's)';
    const intervalId = setInterval(() => {
      countdown.value--;
      countdownText.value = t('global.ReSend') + countdown.value + 's)';
      if (countdown.value <= 0) {
        clearInterval(intervalId);
        countdown.value = 60;
        countdownText.value = t('global.GetCode');
      }
    }, 1000);
    if (forms.email) {
      const { code, data, msg } = await getEmailCode({ email: forms.email });
      ElMessage.success(t('message.GetCodeSuccess'))
    }
  });
}

const rules = reactive({
  username: [
    { required: true, message: t("message.UserNameIsNull"), trigger: "blur" },
  ],
  emailCode: [
    { required: true, message: t("message.CodeIsNull"), trigger: "blur" },
    { pattern: /^[0-9]{6}$/, message: t("message.emailCodeError"), trigger: "blur" },

  ],
  email: [
    { required: true, message: t("message.EmailIsNull"), trigger: "blur" },
    {
      pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: t("message.PleaseInputRightEmail"),
      trigger: "blur",
    },
  ],
  password1: [
    { required: true, message: t("message.PWDIsNull"), trigger: "blur" },
    { min: 8, max: 16, message: t("message.PWDLength"), trigger: "blur" },
    {
      pattern: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,16}$/,
      message: t("message.PWDAa09"),
      trigger: "blur",
    },
  ],
  password2: [
    { required: true, message: t("message.ConfirmPWDIsNull"), trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error(t("message.ConfirmPWDIsNull")));
        } else if (value !== forms.password1) {
          callback(new Error(t("message.PWDDiff")));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

const forms = reactive({
  username: "",
  email: "",
  password1: "",
  password2: "",
  emailCode: "",
});

// 注册提交方法
async function submit() {
  try {
    const valid = await ruleRef.value.validate();
    if (!valid) {
      ElMessage.error(t("message.CheckInput"));
      return false;
    }

    // 输入验证
    if (
      forms.username === "" ||
      forms.email === "" ||
      forms.emailCode === "" ||
      forms.password1 === "" ||
      forms.password2 === ""
    ) {
      ElMessage.error(t("message.InputAll"));
      return;
    }

    if (forms.password1 !== forms.password2) {
      ElMessage.error(t("message.PWDDiff"));
      return;
    }

    // 注册请求
    const { code, msg } = await register({
      username: forms.username,
      email: forms.email,
      emailCode: forms.emailCode,
      password: forms.password1,
    });

    if (code === 200) {
      ElMessage.success(t("message.RegSuccess"));
      await router.push("/login");
    } else {
      ElMessage.error(msg);
    }
  } catch (error) {
    console.log(error);
  }
}
</script>

<style scoped lang="less">
//element plus样式 start
.el-form {
  :deep(.el-select__wrapper) {
    height: .42rem;
    border-radius: 8px;
  }

  :deep(.el-input__wrapper) {
    border-radius: 8px;
  }

  :deep(.el-input) {
    height: .42rem;
  }

  :deep(.submit_btn) {
    border-radius: 8px;
    width: 3rem;
    height: .42rem;
  }
}

.example-showcase .el-dropdown+.el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

//element plus样式 end

/****** 底部“简体中文按钮” ******/
.simpleChinese.is-text:not(.is-disabled):focus-visible {
  outline: none;
}
</style>
